<?php

namespace teach\controllers;


use teach\service\Publicly;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class PubliclyController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 用户绑定
     * @return \yii\web\Response
     */
    public function actionBinding()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid'); //商家id
        $uid = $request->post('uid');  //当前用户
        $sid = $request->post('sid');  //上级id

        $msg = '';
        $flag = false;
        if (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$uid) {
            $msg = 'uid 用户id不能为空';
        } elseif (!$sid) {
            $msg = 'sid 上级id不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $publicly = new Publicly();

            //查找出当前用户是否已经绑定过了
            $where = " id = {$uid} ";
            $user = $publicly->userOne($where);

            //判断当前用户是否合法存在
            if (!$user) {
                $jsonData = ResponseHelper::buildJsonData(400, '用户不存在');
                return $this->asJson($jsonData);
            }

            //当前用户是否是商家
            if ($user['mall_is'] == 1) {
                $jsonData = ResponseHelper::buildJsonData(400, '当前用户是商家');
                return $this->asJson($jsonData);
            }

            $time = time();
            //判断是否绑定
            if ($user['mall_id']) {
                //判断创建时间跟进入商店的时间是否一样,如果是一样的可以改绑
                if ($user['create_time'] != $user['mall_create_time']) {
                    $jsonData = ResponseHelper::buildJsonData(400, '当前用户已经绑定商家');
                    return $this->asJson($jsonData);
                }

                //进入时间跟绑定时间是一样的情况下 判断是否下过单，下过单的说明不能改 可以变更下用户进入商城的时间
                if ($user['create_time'] == $user['mall_create_time']) {
                    $whereStr = " uid = {$uid} AND mid = {$user['mall_id']}";
                    $count = $publicly->haveOrder($whereStr);
                    if ($count > 0) {
                        //更新时间 说明已经购买过了 不能更新绑定
                        $andWhereStr = " mall_create_time = {$time}";
                        $mapStr = " id = {$uid} ";
                        $publicly->mallCreateTime($mapStr, $andWhereStr);
                        $jsonData = ResponseHelper::buildJsonData(400, '当前用户已经绑定');
                        return $this->asJson($jsonData);
                    }
                }


            }

            //判断上级跟自身是否是同一个用户否则不给绑定
            if ($uid == $sid) {
                $jsonData = ResponseHelper::buildJsonData(400, '当前用户不可以绑定自己');
                return $this->asJson($jsonData);
            }


            //如果是 mid == sid 说明是商家自己分享的，直接绑定到商家id就行了
            if ($mid == $sid) {
                $map = " mall_id = {$mid}, mall_create_time = {$time}  ";
                $res = $publicly->userBinding($map, $where);
                if ($res) {
                    $jsonData = ResponseHelper::buildJsonData(200, '绑定成功 .1');
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '绑定失败 .1');
                }

            } else {
                //如果 mid != sid 说明是分销商分享的，则需要绑定 上级跟 商家id

                //在非商家分享时,查找sid的上级,如果有就入库到这个用户中
                //查找分享者
                $andWhere = " id = {$sid} ";
                $superiorUser = $publicly->userOne($andWhere);
                if ($superiorUser) {

                    //定义积分
                    $superScore = 100;
                    $topScore = 50;
                    //判断分享者是否有上级
                    if ($superiorUser['mall_superior']) {
                        //有上级
                        $mapper = " mall_id = {$mid}, mall_superior = {$sid}, mall_top = {$superiorUser['mall_superior']}, mall_create_time = {$time} ";
                        $result = $publicly->userBinding($mapper, $where);
                        if ($result) {
                            //给分销商的下级加一 TODO 上级加上积分100 上上级加上积分50 跟星级值
                            $param = " mall_brother_count = mall_brother_count + 1, score = score + {$superScore},  score_total = score_total + {$superScore} ";
                            $parameter = " id = {$sid} ";
                            $publicly->superiorAdd($param, $parameter);

                            //给上上级加上积分跟星级值
                            $paramStr = " score = score + 50,  score_total = score_total + {$topScore} ";
                            $parameterStr = " id = {$superiorUser['mall_superior']} ";
                            $publicly->superiorAdd($paramStr, $parameterStr);

                            //TODO 加上积分记录
                            $mapScoreSuper = [
                                'uid' => $sid,
                                'fid' => $uid,
                                'mid' => $mid,
                                'score' => $superScore,
                                'des' => '获得下级',
                                'create_time' => time(),
                            ];
                            $publicly->scoreRecord($mapScoreSuper);
                            $mapScoreTop = [
                                'uid' => $superiorUser['mall_superior'],
                                'fid' => $uid,
                                'mid' => $mid,
                                'score' => $topScore,
                                'des' => '获得下下级',
                                'create_time' => time(),
                            ];
                            $publicly->scoreRecord($mapScoreTop);
                            $jsonData = ResponseHelper::buildJsonData(200, '绑定成功 .2');
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(400, '绑定失败 .2');
                        }
                    } else {
                        //无上级
                        $map = " mall_id = {$mid}, mall_superior = {$sid}, mall_create_time = {$time} ";
                        $res = $publicly->userBinding($map, $where);
                        if ($res) {
                            //给上级分销商加一 TODO 上级加上积分100
                            $param = " mall_brother_count = mall_brother_count + 1, score = score + {$superScore}, score_total = score_total + {$superScore} ";
                            $parameter = " id = {$sid} ";
                            $publicly->superiorAdd($param, $parameter);

                            //加上记录
                            $mapScoreSuper = [
                                'uid' => $sid,
                                'fid' => $uid,
                                'mid' => $mid,
                                'score' => $superScore,
                                'des' => '获得下级',
                                'create_time' => time(),
                            ];
                            $publicly->scoreRecord($mapScoreSuper);
                            $jsonData = ResponseHelper::buildJsonData(200, '绑定成功 .3');
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(400, '绑定失败 .3');
                        }
                    }

                } else {
                    //分享者不存在
                    $jsonData = ResponseHelper::buildJsonData(400, '分享者不存在,绑定失败');
                }
            }
        }

        return $this->asJson($jsonData);
    }
}